package com.gitee.ywj1352.dubbo.resilience4j.config;

import io.github.resilience4j.bulkhead.ThreadPoolBulkhead;
import io.github.resilience4j.bulkhead.ThreadPoolBulkheadConfig;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BulkheadFactory {
    private BulkheadFactory() {
    }

    private static BulkheadFactory singleton = new BulkheadFactory();
    private Map<String, ThreadPoolBulkhead> map = new ConcurrentHashMap<String, ThreadPoolBulkhead>();


    public static BulkheadFactory getSingleton() {
        return singleton;
    }

    public ThreadPoolBulkhead getThreadPoolBulkheadFactory(Invoker<?> invoker, String methodName) {
        URL url = invoker.getUrl();

        return map.computeIfAbsent(methodName, k -> {
            ThreadPoolBulkheadConfig config = ThreadPoolBulkheadConfig.custom()
                    .maxThreadPoolSize(url.getParameter("maxThreadPoolSize", 10))
                    .coreThreadPoolSize(url.getParameter("coreThreadPoolSize", 10))
                    .queueCapacity(url.getParameter("queueCapacity", 20))
                    .build();
            return ThreadPoolBulkhead.of(methodName, config);
        });
    }


}
